package com.cwits.wifi.util;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;

import com.cwits.wifi.data.beans.FileInfo;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by bob on 15-12-28.
 */
public class AppUtil {
    private static List<FileInfo> allLocalFile = new ArrayList<>();


    public static final int UPGRADE_APK_TYPE = 0;
    public static final int UPGRADE_SDK_TYPE = 1;

    public static double getDeviceVersionInfo(String filename, int type, boolean outFtp){
        String result;
        String[] strs;
        int index = 0;
        try{
            if(filename != null){
                if(filename.contains(",")) {
                    switch (type){
                        case UPGRADE_APK_TYPE:
                            if(outFtp){
                                index = 1;
                            }else{
                                index = 2;
                            }
                            break;
                        case UPGRADE_SDK_TYPE:
                            if(outFtp){
                                index = 0;
                            }else{
                                index = 1;
                            }
                            break;
                    }
                    strs = filename.split(",");
                    if(strs[index].contains("[")){
                        result = strs[index].substring(strs[index].indexOf("[") + 1);
                        if(result.contains("]")){
                            result = result.substring(0,result.indexOf("]"));
                            return Double.parseDouble(result);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0.0;
    }

    public static String getDeviceFirmwarePath(String filename){
        String result = "";
        try{
            if(filename != null){
                if(filename.contains(",")){
                    String[] strs = filename.split(",");
                    result = strs[0];
                    return result;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static boolean isAppInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > 20) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    /**
     * 防止多次点击事件
     * **/
    private static long lastClickTime;
    public static boolean isFastDoubleClick(int delayTime) {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime > delayTime) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static void deleteFile(File file) {
        if(file == null || !file.exists()){
            return;
        }
        if (file.isFile()) {
            if(file.delete()){
                System.out.printf("delete file success!");
            }
            return;
        }
        if(file.isDirectory()){
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                if(file.delete()){
                    System.out.printf("delete empty file success!");
                }
                return;
            }
            for (File childFile :childFiles) {
                deleteFile(childFile);
            }
            if(file.delete()){
                System.out.printf("delete empty file success!");
            }
        }
    }

    public static Double getUpgradeFileVersion(String filename){
        String result = "";
        String[] strs = filename.split(",");
        try{
            if(strs[0].contains("[")){
                result = strs[0].substring(strs[0].indexOf("[") + 1);
                if(result.contains("]")){
                    result = result.substring(0,result.indexOf("]"));
                    return Double.parseDouble(result);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0.0;
    }

    public static Double getDeviceAPKVersion(String filename){
        String result = "";
        String[] strs = filename.split(",");
        try{
            if(strs[1].contains("[")){
                result = strs[1].substring(strs[1].indexOf("[") + 1);
                if(result.contains("]")){
                    result = result.substring(0,result.indexOf("]"));
                    return Double.parseDouble(result);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0.0;
    }

    //从resources中的raw 文件夹中获取文件并读取数据
    public static String getFromRaw(Context mcontext, int rawId){
        String result = "";
        try {
            InputStream in = mcontext.getResources().openRawResource(rawId);
            //获取文件的字节数
            int lenght = in.available();
            //创建byte数组
            byte[]  buffer = new byte[lenght];
            //将文件中的数据读到byte数组中
            in.read(buffer);
            result = new String(buffer, "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static List<FileInfo> getAllLocalFile(String path){
        if(allLocalFile == null){
            allLocalFile = new ArrayList<>();
        }else{
            if(allLocalFile.size() > 0){
                allLocalFile.clear();
            }
        }
        if(path == null || path.isEmpty()){
            return allLocalFile;
        }
        try{
            File defaultFolder = new File(path);
            if(defaultFolder.exists()){
                if(defaultFolder.isDirectory()){
                    File[] files = defaultFolder.listFiles();
                    for (File file : files){
                        if(file.getName().equals("download")){
                            //File[] subFiles = file.listFiles();
                            //for (File subFile : subFiles){
                                //if(subFile.getName().equals("download")){
                                    allLocalFile.addAll(getLocalFileInfo(file.getPath()));
                                //}
                           // }
                        }else{
                            FileInfo info = new FileInfo();
                            //info.setTitle(getFileName(file.getName()));
                            info.setTitle(file.getName());
                            info.setDirectory(false);
                            info.setSize(file.length());
                            info.setCreateDate(getFileCreatTime(file.getName()));
                            info.setPath(file.getPath());
                            allLocalFile.add(info);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return allLocalFile;
    }

    public static List<FileInfo> getLocalFileInfo(String path){
        List<FileInfo> resultList = new ArrayList<>();
        if(path == null || path.isEmpty()){
            return resultList;
        }
        try{
            File defaultFolder = new File(path);
            if(defaultFolder.exists()){
                if (defaultFolder.isDirectory()){
                    File[] files = defaultFolder.listFiles();
                    if(files != null && files.length > 0){
                        String[] fileNames = new String[files.length];
                        for (int i = 0; i < files.length; i++){
                            fileNames[i] = files[i].getName();
                        }
                        sort(fileNames);
                        for (String fileName: fileNames){
                            for (File file : files){
                                if(file.isFile() && file.getName().equals(fileName)){
                                    FileInfo info = new FileInfo();
                                    //info.setTitle(getFileName(file.getName()));
                                    info.setTitle(file.getName());
                                    info.setDirectory(false);
                                    info.setSize(file.length());
                                    info.setCreateDate(getFileCreatTime(file.getName()));
                                    info.setPath(file.getPath());
                                    resultList.add(info);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultList;
    }

    public static String getFileName(String drs){
        String result = null;
        if(drs == null || drs.isEmpty()){
            return null;
        }
        String fileType = "";
        if(drs.contains(".")){
            fileType = drs.substring(drs.indexOf("."));
        }
        if(drs.contains("_")){
            String[] strs = drs.split("_");
            result = strs[0];
        }
        return result + fileType;
    }

    public static String getFileCreatTime(String drs){
        String result = null;
        if(drs == null || drs.isEmpty()){
            return null;
        }
        if(drs.contains("_")){
            String[] strs = drs.split("_");
            if(strs[1].length() >= 14){
                String time = strs[1];
                result = time.substring(0, 4)  +time.substring(4, 6)+time.substring(6,8)
                        +" "+time.substring(8,10)+":"+time.substring(10,12)+":"+time.substring(12,14);
            }
        }
        return result;
    }

    /**
     * desc sort
     */
    public static String[] sort(String[] drs){
        if(drs == null || drs.length == 0){
            return drs;
        }
        for (int i = 0; i < drs.length-1; i++) {
            for (int j = i+1; j < drs.length; j++) {
                if(drs[j].compareTo(drs[i]) > 0){
                    String temp = drs[j];
                    drs[j] = drs[i];
                    drs[i] = temp;
                }
            }
        }
        return drs;
    }
}
